/**
 * 
 */
package com.taobao.snowsnow.taobao;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.tree.DefaultElement;

import com.taobao.api.ApiException;
import com.taobao.api.request.TradeFullinfoGetRequest;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.request.TradesSoldIncrementGetRequest;
import com.taobao.api.response.TradeFullinfoGetResponse;
import com.taobao.api.response.TradesSoldGetResponse;
import com.taobao.api.response.TradesSoldIncrementGetResponse;
import com.taobao.snowsnow.hibernate.pojo.Address;
import com.taobao.snowsnow.hibernate.pojo.Buyyer;
import com.taobao.snowsnow.hibernate.pojo.Category;
import com.taobao.snowsnow.hibernate.pojo.Color;
import com.taobao.snowsnow.hibernate.pojo.Contact;
import com.taobao.snowsnow.hibernate.pojo.Dimension;
import com.taobao.snowsnow.hibernate.pojo.Orders;
import com.taobao.snowsnow.hibernate.pojo.Product;
import com.taobao.snowsnow.hibernate.pojo.ProductCollect;
import com.taobao.snowsnow.hibernate.pojo.Trade;
import com.taobao.snowsnow.hibernate.pojo.Type;
import com.taobao.snowsnow.hibernate.service.BuyyerService;
import com.taobao.snowsnow.hibernate.service.CategoryService;
import com.taobao.snowsnow.hibernate.service.ColorService;
import com.taobao.snowsnow.hibernate.service.ContactService;
import com.taobao.snowsnow.hibernate.service.DimensionService;
import com.taobao.snowsnow.hibernate.service.ProductCollectService;
import com.taobao.snowsnow.hibernate.service.ProductService;
import com.taobao.snowsnow.hibernate.service.TradeService;
import com.taobao.snowsnow.hibernate.service.TypeService;
import com.taobao.snowsnow.util.ApplicationContextUtil;
import com.taobao.snowsnow.util.Lazy;
import com.taobao.snowsnow.util.SpringServiceInit;
import com.taobao.snowsnow.util.Util;

/**
 * @author qinanhg 创建日期: 2012-3-10 上午1:19:11 修改时间: 2012-8-27 上午10:30:33
 */
public class TradeSync extends Taobao {

	private ProductCollectService productCollectService;
	private ProductService productService;
	private ContactService contactService;
	private ColorService colorService;
	private DimensionService dimensionService;
	private TradeService tradeService;
	private CategoryService categoryService;
	private TypeService typeService;
	private BuyyerService buyyerService;

	private SpringServiceInit service;

	private Lazy lazy;

	private int updateTradeNum = 0;

	private boolean debug = false;

	private int count;

	/*
	 * <p>等待买家付款
	 */
	public static final int WAIT_BUYER_PAY = 1;

	/*
	 * <p>等待卖家发货,即:买家已付款
	 */
	public static final int WAIT_SELLER_SEND_GOODS = 2;

	/*
	 * <p>等待买家确认收货,即:卖家已发货
	 */
	public static final int WAIT_BUYER_CONFIRM_GOODS = 3;

	/*
	 * <p>交易成功
	 */
	public static final int TRADE_FINISHED = 4;

	/*
	 * <p>付款以前，卖家或买家主动关闭交易
	 */
	public static final int TRADE_CLOSED_BY_TAOBAO = 5;

	/*
	 * <p>付款以后用户退款成功，交易自动关闭
	 */
	public static final int TRADE_CLOSED = 6;

	/*
	 * <p>买家已签收,货到付款专用
	 */
	public static final int TRADE_BUYER_SIGNED = 7;

	/*
	 * <p>没有创建支付宝交易
	 */
	public static final int TRADE_NO_CREATE_PAY = 8;

	// 同步增量模式
	public static final int SYNC_INCREMENT_MODE = 9;

	// 普通的同步模式
	public static final int SYNC_NORMAL_MODE = 10;

	public TradeSync() {
		initService();
	}

	public TradeSync(int syncMode, SpringServiceInit springService)
			throws Exception {
		this.service = springService;
		debug = true;
		initService();
		getTrades(syncMode);
		if (lazy != null)
			lazy.close();
		if (debug)
			System.out.println(count);
	}

	public TradeSync(int syncMode, SpringServiceInit springService, Date start,
			Date end) throws Exception {
		this.service = springService;
		initService();
		getTrades(syncMode, start, end);
		if (lazy != null)
			lazy.close();
	}

	/**
	 * <p>
	 * 批量获取获取多个订单
	 * @throws Exception 
	 */
	private void getTrades(int syncMode) throws Exception {
		getTrades(syncMode, null, null);
	}

	private void getTrades(int syncMode, Date start, Date end) throws Exception {
		List<DefaultElement> list = null;

		long max_page = (getTradeNum(syncMode, start, end) / 40) + 1;

		/*
		 * 页码。取值范围:大于零的整数;默认值:1。注：必须采用倒序的分页方式（从最后一页往回取）才能避免漏单问题。
		 */
		for (long i = max_page; i >= 1; i--) {
			if (syncMode == SYNC_INCREMENT_MODE) {
				list = syncByIncrement(i);
			} else if (syncMode == SYNC_NORMAL_MODE) {
				list = syncByNormal(i, start, end);
			}

			for (DefaultElement trades_element : list) {
				long tid = Long.valueOf(trades_element.elementText("tid"));
				count++;
				// 判断订单和数据库的是否一样
				if (!existedTid(tid)) {
					getTrade(tid);
				}

				else {
					// 更新订单状态
					updateTrade(trades_element, tid);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	private List<DefaultElement> syncByIncrement(long page)
			throws ApiException, DocumentException {
		TradesSoldIncrementGetRequest req = new TradesSoldIncrementGetRequest();

		req.setFields("tid, status");
		/*
		 * 每页条数。取值范围：1~100，默认值：40。建议使用40~50，可以提高成功率，减少超时数量。
		 */
		req.setPageSize(40l);
		req.setPageNo(page);

		// 设置订单查询时间
		// TradesSoldIncrement只能查询1天的订单,所以设置查询的日期为今天和昨天
		Calendar now = Calendar.getInstance();
		req.setEndModified(now.getTime());
		now.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH) - 1);
		req.setStartModified(now.getTime());

		TradesSoldIncrementGetResponse response = client.execute(req,
				TaoBaoUtil.SESSIONKEY);
		Document document = DocumentHelper.parseText(response.getBody());
		return document
				.selectNodes("//trades_sold_increment_get_response/trades/trade");
	}

	@SuppressWarnings("unchecked")
	private List<DefaultElement> syncByNormal(long page, Date start, Date end)
			throws ApiException, DocumentException {
		TradesSoldGetRequest req = new TradesSoldGetRequest();
		req.setFields("tid, status");
		req.setPageSize(40l);
		req.setPageNo(page);

		if (start != null)
			req.setStartCreated(start);
		if (end != null)
			req.setEndCreated(end);

		TradesSoldGetResponse response = client.execute(req,
				TaoBaoUtil.SESSIONKEY);

		Document document = DocumentHelper.parseText(response.getBody());
		return document.selectNodes("//trades_sold_get_response/trades/trade");
	}

	/**
	 * <p>
	 * 获取订单的总数
	 * 
	 * @return 订单总数
	 * @throws DocumentException
	 * @throws ApiException
	 */
	private long getTradeNum(int syncMode) throws DocumentException,
			ApiException {
		return getTradeNum(syncMode, null, null);
	}

	/**
	 * <p>
	 * 按日期查找获取订单
	 * 
	 * @param syncMode
	 *            同步模式
	 * @param start
	 *            开始日期
	 * @param end
	 *            结束日期
	 * @return 找到的记录总数
	 * @throws DocumentException
	 * @throws ApiException
	 */
	private long getTradeNum(int syncMode, Date start, Date end)
			throws DocumentException, ApiException {
		long total_results = 0l;

		if (syncMode != SYNC_INCREMENT_MODE) {
			TradesSoldGetRequest req = new TradesSoldGetRequest();
			req.setFields("tid");
			req.setPageSize(1l);

			if (start != null)
				req.setStartCreated(start);
			if (end != null)
				req.setEndCreated(end);

			TradesSoldGetResponse response = client.execute(req,
					TaoBaoUtil.SESSIONKEY);
			//

			Document document = DocumentHelper.parseText(response.getBody());

			@SuppressWarnings("unchecked")
			List<DefaultElement> list = document
					.selectNodes("//trades_sold_get_response");

			for (DefaultElement trades_element : list) {
				total_results = Long.valueOf(trades_element
						.elementText("total_results"));
			}
		} else {
			TradesSoldIncrementGetRequest req = new TradesSoldIncrementGetRequest();
			req.setFields("tid");
			req.setPageSize(1l);
			Calendar now = Calendar.getInstance();
			now.set(Calendar.HOUR_OF_DAY, 0);
			now.set(Calendar.MINUTE, 0);
			now.set(Calendar.SECOND, 0);
			req.setEndModified(now.getTime());
			now.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH) - 1);
			req.setStartModified(now.getTime());
			TradesSoldIncrementGetResponse response = client.execute(req,
					TaoBaoUtil.SESSIONKEY);
			Document document = DocumentHelper.parseText(response.getBody());

			@SuppressWarnings("unchecked")
			List<DefaultElement> list = document
					.selectNodes("//trades_sold_increment_get_response");

			for (DefaultElement trades_element : list) {
				total_results = Long.valueOf(trades_element
						.elementText("total_results"));
			}
		}
		return total_results;
	}

	/**
	 * <p>
	 * 初始化数据库服务类
	 */
	private void initService() {

		if (service != null) {
			productCollectService = service.getProductCollectService();
			colorService = service.getColorService();
			dimensionService = service.getDimensionService();
			tradeService = service.getTradeService();
			typeService = service.getTypeService();
			categoryService = service.getCategoryService();
			buyyerService = service.getBuyyerService();
		} else {
			lazy = new Lazy();
			productCollectService = (ProductCollectService) ApplicationContextUtil
					.getBean("ProductCollectService");
			colorService = (ColorService) ApplicationContextUtil
					.getBean("ColorService");
			dimensionService = (DimensionService) ApplicationContextUtil
					.getBean("DimensionService");
			tradeService = (TradeService) ApplicationContextUtil
					.getBean("TradeService");
			typeService = (TypeService) ApplicationContextUtil
					.getBean("TypeService");
			categoryService = (CategoryService) ApplicationContextUtil
					.getBean("CategoryService");
			buyyerService = (BuyyerService) ApplicationContextUtil
					.getBean("BuyyerService");
			contactService = (ContactService) ApplicationContextUtil
					.getBean("ContactService");
		}
	}

	/**
	 * 获取单个订单信息
	 * 
	 * @param tid
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private void getTrade(long tid) throws Exception {

		TradeFullinfoGetRequest req = new TradeFullinfoGetRequest();
		req.setFields("seller_nick,buyer_nick,post_fee,title,buyer_message,payment,seller_memo,type,created,sid,tid,buyer_rate,status,payment,pay_time,end_time,modified,consign_time,received_payment,num_iid,num_iid,num,price,cod_fee,cod_status,shipping_type,receiver_name,receiver_state,receiver_city,receiver_district,receiver_address,receiver_zip,receiver_mobile,receiver_phone,orders.title,orders.price,orders.pic_path,orders.price,orders.num,orders.iid,orders.num_iid,orders.sku_id,orders.refund_status,orders.status,orders.oid,orders.total_fee,orders.payment,orders.discount_fee,orders.adjust_fee,orders.sku_properties_name,orders.item_meal_name,orders.buyer_rate,orders.seller_rate,orders.outer_iid,orders.outer_sku_id,orders.refund_id,orders.seller_type");
		req.setTid(tid);

		TradeFullinfoGetResponse response = client.execute(req,
				TaoBaoUtil.SESSIONKEY);

		Document document = DocumentHelper.parseText(response.getBody());

		List<DefaultElement> list = document
				.selectNodes("//trade_fullinfo_get_response/trade");

		for (DefaultElement trade_element : list) {
			Trade trade = createTrade(trade_element, tid);
			if (trade != null) {
				tradeService.create(trade);
				setUpdateTradeNum(getUpdateTradeNum() + 1);
			}
		}
	}

	/**
	 * <p>
	 * 创建trade
	 * 
	 * @param trade_element
	 *            交易的节点元素
	 * @param tid
	 *            交易编号
	 * @return 新建的交易
	 * @throws Exception
	 */
	private Trade createTrade(DefaultElement trade_element, long tid)
			throws Exception {
		Trade trade = null;

		String buyer_nick = trade_element.elementText("buyer_nick");
		String buyer_message = trade_element.elementText("buyer_message");
		String seller_memo = trade_element.elementText("seller_memo");
		String total_fee = trade_element.elementText("payment");
		String post_fee = trade_element.elementText("post_fee");

		/*
		 * 1. WAIT_BUYER_PAY 2. WAIT_SELLER_SEND_GOODS 3.
		 * WAIT_BUYER_CONFIRM_GOODS 4. TRADE_FINISHED 5. TRADE_CLOSED_BY_TAOBAO
		 */
		int status = Util.getTradeStringsInt(trade_element
				.elementText("status"));
		String createTime = trade_element.elementText("created");
		String pay_time = trade_element.elementText("pay_time");

		// 不同步已经关闭的订单
		if (status != TRADE_CLOSED_BY_TAOBAO && status != TRADE_CLOSED) {
			boolean compareStatus = false;
			boolean compareStatusCreateTime = false;

			for (Trade t : tradeService.findByTaoBaoID(buyer_nick)) {
				// TODO 如果一个买家买了一单，而后卖家发货了，买家又买了一单时，后面的订单就不能和之前的订单合并了
				// 合并状态为2 3 4的订单,因为这些订单都是已经付款了
				if (getSameStatus(t.getStatus()) == getSameStatus(status)) {
					trade = t;
					compareStatus = true;
					// 如果2个交易的状态一样的话同步
					// 如果2个交易时间相差1天,那么就不合并订单了
					compareStatusCreateTime = tradeTimeThanOneDay(
							Timestamp.valueOf(createTime),
							trade.getCreateTime());
					break;
				}
			}

			// 如果当前买家，之前有拍过一个订单，那么在这里就要把此单和之前的订单合并
			// TODO 如果有一个买家拍了很多订单,但是都没有付款,那么系统同步后,订单就会永久存入数据库,这时就需要人工清理这些订单了
			if (trade != null && compareStatus && compareStatusCreateTime) {
				mergeMultiTrade(String.valueOf(tid), trade, buyer_message,
						seller_memo, Float.valueOf(total_fee));
			}

			// 搜索没有找到，说明当前用户之前没有拍过订单
			else {
				trade = new Trade();

				Buyyer buyyer = buyyerService.findByTaoBaoIDPrecise(buyer_nick);

				if (buyyer == null)
					buyyer = new Buyyer(buyer_nick);
				else
					trade.setDescs("old customer");
				Contact cnt = setBuyyerContact(trade_element);
				buyyer.getContacts().add(cnt);
				cnt.setPeople(buyyer);
				trade.setPeople(buyyer);

				if (buyer_message != null)
					trade.setBuyyerMessage(buyer_message);
				if (seller_memo != null)
					trade.setSellerMemo(seller_memo);

				// 如果是新的交易,在这要填写Tid
				trade.setTid(tid);
				trade.setStatus(status);
				trade.setTotalPrice(Float.valueOf(total_fee));
				trade.setPostFee(Float.valueOf(post_fee));
				trade.setCreateTime(Timestamp.valueOf(createTime));
				if (pay_time != null)
					trade.setPayTime(Timestamp.valueOf(pay_time));
			}

			setBuyyerOrder(trade_element, trade);
		}

		return trade;
	}

	/**
	 * @param status
	 * @return
	 */
	private int getSameStatus(int status) {

		switch (status) {
		case 1:
			return 1;
		case 2:
			return 2;
		case 3:
		case 4:
			return 3;
		case 5:
			return 5;
		default:
			return -1;
		}
	}

	/**
	 * <p>
	 * 更新订单状态
	 * 
	 * @param trade_element
	 *            交易的节点元素
	 * @param tid
	 *            交易编号
	 * @throws Exception
	 */
	private void updateTrade(DefaultElement trade_element, long tid)
			throws Exception {
		Trade trade = tradeService.findByTid(tid);

		int status = Util.getTradeStringsInt(trade_element
				.elementText("status"));

		if (trade != null) {
			if (status != trade.getStatus()) {
				if (status != TRADE_CLOSED && status != TRADE_CLOSED_BY_TAOBAO) {
					trade.setStatus(status);
					tradeService.saveOrUpdate(trade);
				}
				// 如果订单状态变成关闭状态,直接删除订单
				else {
					// 查找订单的买家是否有多个订单
					int t1 = tradeService.findByTaoBaoID(
							trade.getPeople().getTaobaoId()).size();
					// 如果有多个订单就不删除用户账号
					if (t1 == 1) {
						tradeService.remove(trade);
						buyyerService.remove(buyyerService.findById(trade
								.getPeople().getId()));
					} else
						tradeService.remove(trade);
				}
			}
		}
	}

	/**
	 * <p>
	 * 判断当前订单的时间和之前拍下订单的时间是否相同 如果订单时间相差1天,就视为不同
	 * 
	 * @param current
	 *            当前订单时间
	 * @param older
	 *            之前的订单时间
	 * @return Yes Or No
	 */
	private boolean tradeTimeThanOneDay(Timestamp current, Timestamp older) {

		final long dayTime = 1000 * 60 * 60 * 24;

		long diff = (current.getTime() - older.getTime()) / dayTime;

		return diff > 1 ? false : true;
	}

	/**
	 * 添加订单到交易里
	 * 
	 * @param trade_element
	 *            交易的节点元素
	 * @param trade
	 *            要添加订单的交易
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private void setBuyyerOrder(DefaultElement trade_element, Trade trade)
			throws Exception {

		Orders order = null;

		// 获取交易中的订单
		Element orders_element = trade_element.element("orders");

		ProductCollect productCollect = null;
		Product product = null;

		for (DefaultElement order_element : (List<DefaultElement>) orders_element
				.elements("order")) {
			order = new Orders();
			product = new Product();

			long num_iid = Long.valueOf(order_element.elementText("num_iid"));
			productCollect = productCollectService.findByNumIID(Long
					.valueOf(num_iid));

			if (productCollect == null) {
				// TODO
				// 如果这里没有找到productCollect，说明数据库里还没有添加，在此处添加productCollect，这里可以同步商品类，以后就不用productSync了
				new ProductSync(true).createItem(num_iid);
				productCollect = productCollectService.findByNumIID(Long
						.valueOf(num_iid));
			}

			// 获取买家拍下的商品SKU
			String sku_properties_name = order_element
					.elementText("sku_properties_name");
			int num = Integer.valueOf(order_element.elementText("num"));
			float price = Float.valueOf(order_element.elementText("price"));
			
			// 设置商品的颜色, 尺寸等
			setProductColorAndDimension(product, sku_properties_name);

			// 设置Product所属的Item
			product.setProductCollect(productCollect);
			product.setSellingPrice(price);
			order.setQuantity(num);

			// 设置订单的总价钱: 总价钱=购买数量 * 商品单价
			order.setPrice(num * price);
			order.setProduct(product);
			order.setTrade(trade);
			order.setDescs(sku_properties_name);
			trade.getOrders().add(order);
		}
	}

	/**
	 * 设置买家的联系人信息
	 * 
	 * @param trade_element
	 *            交易的节点元素
	 * @return 联系人
	 */
	private Contact setBuyyerContact(DefaultElement trade_element) {
		// 收件人名称
		String receiver_name = trade_element.elementText("receiver_name");
		// 省
		String receiver_state = trade_element.elementText("receiver_state");
		// 市
		String receiver_city = trade_element.elementText("receiver_city");
		// 区
		String receiver_district = trade_element.elementText("receiver_district");
		// 街道
		String receiver_address = trade_element.elementText("receiver_address");
		// 手机
		String receiver_mobile = trade_element.elementText("receiver_mobile");
		// 固定电话
		String receiver_phone = trade_element.elementText("receiver_phone");

		Contact cnt = null;

		// 是否已经存在有联系人
		cnt = contactService.findByName(receiver_name);

		// 没有就新建一个
		if (cnt == null)
			cnt = new Contact(receiver_name);

		if ("".equals(receiver_phone) || receiver_phone != null)
			cnt.setHousePhone(receiver_phone);
		if ("".equals(receiver_mobile) || receiver_mobile != null)
			cnt.setMobile1(receiver_mobile);

		StringBuffer addressBuffer = new StringBuffer();

		if (receiver_state != null)
			addressBuffer.append(receiver_state);
		if (receiver_city != null)
			addressBuffer.append(receiver_city);
		if (receiver_district != null)
			addressBuffer.append(receiver_district);

		addressBuffer.append(receiver_address);

		// 设置联系人的备注为订单拍下的地址,方便以后查对
		cnt.setDescs(addressBuffer.toString());
		
		// TODO 没有和之前的地址比对，如果地址一样不应该再新建address
		
		List<Address> addresses = cnt.getAddresses();
		
		Address address = new Address();

		if (receiver_state != null) {
			Type state = typeService.findByNamePrecise(receiver_state);
			if (state == null) {
				Category category = categoryService.findByNamePrecise("省份");
				if (category == null)
					category = new Category("省份");
				state = new Type(category, receiver_state);
			}
			address.setState(state);
		}

		if (receiver_city != null) {
			Type city = typeService.findByNamePrecise(receiver_city);
			if (city == null) {
				Category category = categoryService.findByNamePrecise("城市");
				if (category == null)
					category = new Category("城市");
				city = new Type(category, receiver_city);
			}
			address.setCity(city);
		}

		if (receiver_district != null) {
			Type district = typeService.findByNamePrecise(receiver_district);
			if (district == null) {
				Category category = categoryService.findByNamePrecise("地区");
				if (category == null)
					category = new Category("地区");
				district = new Type(category, receiver_district);
			}
			address.setDistrict(district);
		}

		address.setAddress(filterAddress(receiver_address, new String[] {
				receiver_state, receiver_city, receiver_district }));

		// 设置关联
		cnt.getAddresses().add(address);
		address.setContact(cnt);

		return cnt;
	}
	
	private void find(List<Address> addresses, String state, String city, String address) {
		
	}

	/**
	 * <p>
	 * 解析SKU后设置Product的颜色和尺寸
	 * 
	 * @param product
	 *            需要设置的Product
	 * @param sku_properties_name
	 *            待解析的SKU字符串属性
	 */
	private void setProductColorAndDimension(Product product,
			String sku_properties_name) {
		Color color = null;
		Dimension dimension = null;
		// 解析Sku设置颜色和尺寸
		if (sku_properties_name != null) {
			SkuParse sku = new SkuParse(sku_properties_name.split(":")[1]);
			String color_str = sku.getColor();
			String dimension_str = sku.getSpecs();

			// 设置Product的颜色
			if (color_str != null) {
				color = colorService.findByNamePrecise(color_str);
				product.setColor(color);
			}

			// 设置Product的尺寸
			if (dimension_str != null) {
				dimension = dimensionService.findByNamePrecise(dimension_str);
				product.setDimension(dimension);
			}
		}
	}

	/**
	 * <p>
	 * 合并多个订单
	 * 
	 * @param tid
	 *            当前的订单号
	 * @param trade
	 *            当前的交易
	 * @param buyer_message
	 *            买家留言
	 * @param seller_memo
	 *            卖家留言
	 * @param price
	 *            订单总价钱
	 */
	private void mergeMultiTrade(String tid, Trade trade, String buyer_message,
			String seller_memo, Float price) {
		// 把买家后来拍的订单单号保存下来,后面发货时要用到
		String tradeTids = trade.getTradeTids();

		if (tradeTids == null) {
			trade.setTradeTids(tid);
		} else {
			trade.setTradeTids(tradeTids + ";" + String.valueOf(tid));
		}

		// 添加买家留言
		if (buyer_message != null) {
			String message = trade.getBuyyerMessage();
			// 合并买家留言
			if (message != null)
				trade.setBuyyerMessage(message + "\n" + buyer_message);
			else
				trade.setBuyyerMessage(buyer_message);
		}

		// 添加卖家留言
		if (seller_memo != null) {
			String memo = trade.getSellerMemo();
			// 合并卖家留言
			if (memo != null)
				trade.setSellerMemo(memo + "\n" + seller_memo);
			else
				trade.setSellerMemo(seller_memo);
		}

		// 累计计算价钱
		trade.setTotalPrice(trade.getTotalPrice() + price);
	}

	/**
	 * <p>
	 * 数据库里是否已经存在有这个交易
	 * 
	 * @param tid
	 *            订单编号
	 * @return yes or no
	 */
	private boolean existedTid(long tid) {
		// 查找是否存在有订单
		Trade t = tradeService.findByTid(tid);

		if (t != null) {
			return true;
		} else {
			// 是否在子订单里面
			t = tradeService.findByMultiTids(tid);
			if (t != null)
				return true;
		}
		return false;
	}

	/**
	 * <p>
	 * 过滤地址,有些地址多写了省市区,在此可以把多余的信息过滤掉
	 * 
	 * @param address
	 *            要过滤的地址
	 * @param filterString
	 *            地址内可能包含的省市区信息,数组格式: [省][市][区]
	 * @return
	 */
	private String filterAddress(String address, String[] filterString) {

		for (int i = filterString.length - 1; i > 0; i--) {
			if (filterString[i] != null) {
				if (address.contains(filterString[i])) {
					int length = 0;
					for (String str : filterString) {
						if (str != null)
							length += str.length();
					}
					address = filterAddressString(address, filterString[i],
							length);
					break;
				}
			} else
				i--;
		}

		return address;
	}

	/**
	 * @param address
	 *            待过滤的字符串
	 * @param filterString
	 *            需要过滤的字符串
	 * @return 过滤好的地址
	 */
	private String filterAddressString(String address, String filterString,
			int length) {
		int index = address.indexOf(filterString);

		if (index == -1)
			return address;

		// 只匹配句首的filterString
		if (index < length + 1) {
			return address.substring(index + filterString.length());
		}

		return address;
	}

	public static void main(String[] args) {
		try {
			Calendar now = Calendar.getInstance();
			Date end = now.getTime();
			now.set(Calendar.DAY_OF_MONTH, now.get(Calendar.DAY_OF_MONTH) - 5);
			Date start = now.getTime();
			new TradeSync(TradeSync.SYNC_NORMAL_MODE, null, start, end);
		} catch (ApiException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public SpringServiceInit getService() {
		return service;
	}

	public void setService(SpringServiceInit service) {
		this.service = service;
	}

	public int getUpdateTradeNum() {
		return updateTradeNum;
	}

	public void setUpdateTradeNum(int updateTradeNum) {
		this.updateTradeNum = updateTradeNum;
	}

}
